package org.chen.controller;

import lombok.RequiredArgsConstructor;
import org.chen.common.exception.ServiceException;
import org.chen.domain.dto.R;
import org.chen.domain.entity.User;
import org.chen.domain.vo.SystemConfigVO;
import org.chen.domain.vo.UserVO;
import org.chen.service.SystemConfigService;
import org.chen.service.UserService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/system")
@RequiredArgsConstructor
public class SystemConfigController {
    
    private final SystemConfigService systemConfigService;
    private final UserService userService;

    /**
     * 获取系统信息，包含系统配置和当前登录用户信息
     */
    @GetMapping("/info")
    public R<SystemConfigVO> getSystemInfo() {
        // 获取系统配置
        SystemConfigVO configVO = systemConfigService.getSystemInfo();
        
        // 获取当前登录用户信息
        UserVO currentUser = userService.getCurrentUserInfo();
        if (currentUser != null) {
            configVO.setUsername(currentUser.getUsername());
            configVO.setEmail(currentUser.getEmail());
        }
        
        return R.ok(configVO);
    }

    /**
     * 更新系统配置信息
     */
    @PutMapping("/info")
    public R<Boolean> updateSystemInfo(@RequestBody @Validated SystemConfigVO configVO) {
        // 权限校验 - 只有管理员可以更新系统配置
        boolean hasPermission = userService.hasPermission("system:config:update");
        if (!hasPermission) {
            throw new ServiceException("没有操作权限");
        }
        
        return R.ok(systemConfigService.updateSystemInfo(configVO));
    }

    /**
     * 获取系统基础信息（无需权限）
     */
    @GetMapping("/basic")
    public R<Map<String, Object>> getBasicInfo() {
        Map<String, Object> info = new HashMap<>();
        SystemConfigVO config = systemConfigService.getSystemInfo();
        info.put("systemName", config.getSystemName());
        info.put("version", "1.0.0");
        return R.ok(info);
    }
}